package org.smart4j.chapter2.controller;


import org.smart4j.chapter2.model.Customer;
import org.smart4j.chapter2.service.CustomerService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@WebServlet("/customer_update")
public class CustomerUpdateServlet extends HttpServlet {

    private CustomerService customerService;

    @Override
    public void init() throws ServletException{
        customerService=new CustomerService();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Map<String, String[]> map1 = req.getParameterMap();
        int id = Integer.parseInt(map1.get("id")[0]);
        Set<Map.Entry<String, String[]>> entries = map1.entrySet();
        Map map2 = new HashMap();
        int count=0;
        for (Map.Entry<String, String[]> m : entries){
            if(count>0)
                map2.put(m.getKey(),m.getValue()[0]);
            count++;
        }
        customerService.updateCustomer(id,map2);
        req.getRequestDispatcher("/customer").forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}
